package com.lagou.edu.message.netty;

import java.util.ArrayList;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import com.corundumstudio.socketio.Configuration;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.listener.ConnectListener;
import com.corundumstudio.socketio.listener.DisconnectListener;
import com.corundumstudio.socketio.SocketIOServer;

@Component
public class NettyServer implements InitializingBean {
	private java.util.List<SocketIOClient> listsClients = new ArrayList<SocketIOClient>();

	private static ThreadPoolExecutor t = new ThreadPoolExecutor(1, 1, 30, TimeUnit.MINUTES,
			new ArrayBlockingQueue<Runnable>(100));
	
	
	public void send(String msg) {
		listsClients.forEach(item->{
			item.sendEvent("hello",msg);
		});
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		Configuration config = new Configuration();
		config.setHostname("localhost");
		config.setPort(9092);
		final SocketIOServer server = new SocketIOServer(config);
		server.addConnectListener(new ConnectListener() {

			@Override
			public void onConnect(SocketIOClient client) {
				var namespace = client.getNamespace();
				listsClients.add(client);
				client.sendEvent("hello", new String("hello world"));
			}
		});
		server.addDisconnectListener(new DisconnectListener() {

			@Override
			public void onDisconnect(SocketIOClient client) {
				listsClients.remove(client);
			}
		});
		server.startAsync();

		Runtime.getRuntime().addShutdownHook(new Thread() {

			@Override
			public void run() {
				listsClients.stream().forEach(item -> {
					item.disconnect();
				});
			}

		});
	}

}
